{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Getting Started: Voice swap application\n",
    "This notebook shows how to use NVIDIA NeMo (https://github.com/NVIDIA/NeMo) to construct a toy demo which will swap a voice in the audio fragment with a computer generated one.\n",
    "\n",
    "At its core the demo does: \n",
    "\n",
    "* Automatic speech recognition of what is said in the file. E.g. converting audio to text\n",
    "* Adding punctuation and capitalization to the text\n",
    "* Generating spectrogram from resulting text\n",
    "* Generating waveform audio from the spectrogram."
   ],
   "metadata": {
    "colab_type": "text",
    "id": "_wIWPxBVc3_O"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Installation\n",
    "NeMo can be installed via simple pip command."
   ],
   "metadata": {
    "colab_type": "text",
    "id": "gzcsqceVdtj3"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "BRANCH = 'main'\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "I9eIxAyKHREB"
   },
   "outputs": [],
   "source": [
    "BRANCH = 'main'\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# Ignore pre-production warnings\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "import nemo\n",
    "# Import Speech Recognition collection\n",
    "import nemo.collections.asr as nemo_asr\n",
    "# Import Natural Language Processing colleciton\n",
    "import nemo.collections.nlp as nemo_nlp\n",
    "# Import Speech Synthesis collection\n",
    "import nemo.collections.tts as nemo_tts\n",
    "# We'll use this to listen to audio\n",
    "import IPython"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "-X2OyAxreGfl"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# Download audio sample which we'll try\n",
    "# This is a sample from LibriSpeech Dev Clean dataset - the model hasn't seen it before\n",
    "Audio_sample = '2086-149220-0033.wav'\n",
    "!wget https://dldata-public.s3.us-east-2.amazonaws.com/2086-149220-0033.wav\n",
    "# Listen to it\n",
    "IPython.display.Audio(Audio_sample)"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "1vC2DHawIGt8"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Instantiate pre-trained NeMo models which we'll use\n",
    "``from_pretrained(...)`` API downloads and initialized model directly from the cloud.\n",
    "\n",
    "We will load audio_sample and convert it to text with QuartzNet ASR model (an action called transcribe).\n",
    "To convert text back to audio, we actually need to generate spectrogram with FastPitch first and then convert it to actual audio signal using the HiFiGAN vocoder."
   ],
   "metadata": {
    "colab_type": "text",
    "id": "zodyzdyTVXas"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# Speech Recognition model - QuartzNet\n",
    "quartznet = nemo_asr.models.EncDecCTCModel.from_pretrained(model_name=\"stt_en_quartznet15x5\").cuda()\n",
    "# Punctuation and capitalization model\n",
    "punctuation = nemo_nlp.models.PunctuationCapitalizationModel.from_pretrained(model_name='punctuation_en_distilbert').cuda()\n",
    "# Spectrogram generator which takes text as an input and produces spectrogram\n",
    "spectrogram_generator = nemo_tts.models.FastPitchModel.from_pretrained(model_name=\"tts_en_fastpitch\").cuda()\n",
    "# Vocoder model which takes spectrogram and produces actual audio\n",
    "vocoder = nemo_tts.models.HifiGanModel.from_pretrained(model_name=\"tts_hifigan\").cuda()"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "f_J9cuU1H6Bn"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Using the models"
   ],
   "metadata": {
    "colab_type": "text",
    "id": "jQSj-IhEhrtI"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# Convert our audio sample to text\n",
    "files = [Audio_sample]\n",
    "raw_text = ''\n",
    "text = ''\n",
    "for fname, transcription in zip(files, quartznet.transcribe(paths2audio_files=files)):\n",
    "  raw_text = transcription\n",
    "\n",
    "# Add capitalization and punctuation\n",
    "res = punctuation.add_punctuation_capitalization(queries=[raw_text])\n",
    "text = res[0]\n",
    "print(f'\\nRaw recognized text: {raw_text}. \\nText with capitalization and punctuation: {text}')"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "s0ERrXIzKpwu"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# A helper function which combines TTS models to go directly from \n",
    "# text to audio\n",
    "def text_to_audio(text):\n",
    "  parsed = spectrogram_generator.parse(text)\n",
    "  spectrogram = spectrogram_generator.generate_spectrogram(tokens=parsed)\n",
    "  audio = vocoder.convert_spectrogram_to_audio(spec=spectrogram)\n",
    "  return audio.to('cpu').detach().numpy()"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "-0Sk0C9-LmAR"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Results"
   ],
   "metadata": {
    "colab_type": "text",
    "id": "Q8Jvwe4Ahncx"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# This is our original audio sample\n",
    "IPython.display.Audio(Audio_sample)"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "-im5TDF-MP2N"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# This is what was recognized by the ASR model\n",
    "print(raw_text)"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "SNOMquwviEEQ"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# This is how punctuation model changed it\n",
    "print(text)"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "6qRpDPfNiLOU"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "Compare how the synthesized audio sounds when using text with and without punctuation."
   ],
   "metadata": {
    "colab_type": "text",
    "id": "di2IzMsdiiWq"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# Without punctuation\n",
    "IPython.display.Audio(text_to_audio(raw_text), rate=22050)"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "EIh8wTVs5uH7"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "# Final result - with punctuation\n",
    "IPython.display.Audio(text_to_audio(text), rate=22050)"
   ],
   "outputs": [],
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "_qgKa9L954bJ"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Next steps\n",
    "A demo like this is great for prototyping and experimentation. However, for real production deployment, you would want to use a service like [NVIDIA Riva](https://developer.nvidia.com/riva).\n",
    "\n",
    "**NeMo is built for training.** You can fine-tune, or train from scratch on your data all models used in this example. We recommend you checkout the following, more in-depth, tutorials next:\n",
    "\n",
    "* [NeMo fundamentals](https://colab.research.google.com/github/NVIDIA/NeMo/blob/stable/tutorials/00_NeMo_Primer.ipynb)\n",
    "* [NeMo models](https://colab.research.google.com/github/NVIDIA/NeMo/blob/stable/tutorials/01_NeMo_Models.ipynb)\n",
    "* [Speech Recognition](https://colab.research.google.com/github/NVIDIA/NeMo/blob/stable/tutorials/asr/ASR_with_NeMo.ipynb)\n",
    "* [Punctuation and Capitalization](https://colab.research.google.com/github/NVIDIA/NeMo/blob/stable/tutorials/nlp/Punctuation_and_Capitalization.ipynb)\n",
    "* [Speech Synthesis](https://colab.research.google.com/github/NVIDIA/NeMo/blob/stable/tutorials/tts/Inference_ModelSelect.ipynb)\n",
    "\n",
    "\n",
    "You can find scripts for training and fine-tuning ASR, NLP and TTS models [here](https://github.com/NVIDIA/NeMo/tree/main/examples). "
   ],
   "metadata": {
    "colab_type": "text",
    "id": "JOEFYywbctbJ"
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "That's it folks! Head over to NeMo GitHub for more examples: https://github.com/NVIDIA/NeMo"
   ],
   "metadata": {
    "colab_type": "text",
    "id": "ahRh2Y0Lc0G1"
   }
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "NeMo voice swap app",
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
